package com.tinckay.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.tinckay.common.constant.ProjectConstant;
import com.tinckay.common.constant.RedisConstant;
import com.tinckay.common.constant.RegexConstant;
import com.tinckay.common.util.IPUtils;
import com.tinckay.common.util.SendMsgUtils;
import com.tinckay.common.util.ShiroUtils;
import com.tinckay.common.util.ToolUtils;
import com.tinckay.common.util.vcode.Captcha;
import com.tinckay.common.util.vcode.GifCaptcha;
import com.tinckay.service.RedisService;
import io.swagger.annotations.*;
import cn.hutool.core.util.StrUtil;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Jean
 * @Desc:
 * @Date: 2018/11/5 18:01
 */
@Api(tags = "公共模块")
@RestController
public class CommonController extends ApiController {

    Logger logger = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/refresh")
    public String test() {
        return "";
    }

    @ApiOperation("获取验证码")
    @GetMapping(value = "/gifCode")
    public void getGifCode(HttpServletResponse response) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");

            Captcha captcha = new GifCaptcha(146, 33, 4);
            captcha.out(response.getOutputStream());

            Session session = ShiroUtils.getSession();
            session.removeAttribute(ProjectConstant.CAPTCHA_VALID_CODE);
            session.setAttribute(ProjectConstant.CAPTCHA_VALID_CODE, captcha.text().toLowerCase());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("短信验证码")
    @GetMapping("/sendMsg")
    @ApiImplicitParam(name = "mobilePhone", value = "手机号", required = true, dataType = "string", paramType = "query", defaultValue = "")
    public R sendMsg(@RequestParam(value = "mobilePhone") String mobilePhone, HttpServletRequest request) {
        if (!mobilePhone.matches(RegexConstant.MOBILE_PHONE)) {
            return failed("手机号验证有误");
        }

        String ipAddr = IPUtils.getIpAddr(request);
        String cacheRedisKey = RedisConstant.SEND_MESSAGE + mobilePhone;
        String existIp = (String) redisService.getValue(cacheRedisKey);
        if (StrUtil.isNotBlank(existIp) && ipAddr.equals(existIp)) {
            return failed("获取短信过于频繁");
        }

        SendSmsResponse smsResponse = null;

        try {
            String successFlag = "OK";
            int validCode = ToolUtils.getValidCode();
            smsResponse = SendMsgUtils.sendSms(mobilePhone, validCode);

            if (successFlag.equals(smsResponse.getCode())) {
                redisService.setValue(mobilePhone, String.valueOf(validCode), 20, TimeUnit.MINUTES);
                redisService.setValue(cacheRedisKey, ipAddr, 1, TimeUnit.MINUTES);
                return success(smsResponse);
            }
            return failed(smsResponse.getMessage());
        } catch (ClientException e) {
            logger.warn(e.getErrMsg());
            return failed(smsResponse.getMessage());
        }
    }

}
